package com.example.javasystem.service.impl;

import com.example.javasystem.entity.ETable;
import com.example.javasystem.entity.PreprocessingConfig;
import com.example.javasystem.mapper.PreprocessingMapper;
import com.example.javasystem.service.IDataPreprocessingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

@Service
public class DataPreprocessingService implements IDataPreprocessingService {
    @Autowired
    private PreprocessingMapper preproMapper;

    PreprocessingConfig defaultValue;

    // 成员变量暂不初始化
    private BigDecimal tempMin;
    private BigDecimal tempMax;
    private BigDecimal phMin;
    private BigDecimal phMax;
    private BigDecimal aceticMin;
    private BigDecimal aceticMax;
    private BigDecimal alcoholMin;
    private BigDecimal alcoholMax;

    // 依赖注入完成后执行
    @PostConstruct
    public void init() {
        defaultValue = preproMapper.selectDefaultValue();
        // 初始化成员变量
        tempMin = defaultValue.getTempMin();
        tempMax = defaultValue.getTempMax();
        phMin = defaultValue.getPhMin();
        phMax = defaultValue.getPhMax();
        aceticMin = defaultValue.getAceticMin();
        aceticMax = defaultValue.getAceticMax();
        alcoholMin = defaultValue.getAlcoholMin();
        alcoholMax = defaultValue.getAlcoholMax();
    }

    // 新增设置配置的方法
    public boolean updateConfig(PreprocessingConfig config, Integer storage) {
        if (config.getTempMin() != null) {
            this.tempMin = config.getTempMin();
        }
        if (config.getTempMax() != null) {
            this.tempMax = config.getTempMax();
        }
        if (config.getPhMin() != null) {
            this.phMin = config.getPhMin();
        }
        if (config.getPhMax() != null) {
            this.phMax = config.getPhMax();
        }
        if (config.getAceticMin() != null) {
            this.aceticMin = config.getAceticMin();
        }
        if (config.getAceticMax() != null) {
            this.aceticMax = config.getAceticMax();
        }
        if (config.getAlcoholMin() != null) {
            this.alcoholMin = config.getAlcoholMin();
        }
        if (config.getAlcoholMax() != null) {
            this.alcoholMax = config.getAlcoholMax();
        }

        // 持久化存储
        if(storage == 1)
        {
            return preproMapper.isStorage(tempMin, tempMax, phMin, phMax, aceticMin, aceticMax, alcoholMin, alcoholMax);
        }

        return true;
    }

    // 新增获取当前配置的方法
    public PreprocessingConfig getCurrentConfig() {
        PreprocessingConfig config = new PreprocessingConfig();
        config.setTempMin(tempMin);
        config.setTempMax(tempMax);
        config.setPhMin(phMin);
        config.setPhMax(phMax);
        config.setAceticMin(aceticMin);
        config.setAceticMax(aceticMax);
        config.setAlcoholMin(alcoholMin);
        config.setAlcoholMax(alcoholMax);
        return config;
    }

    /**
     * 检查异常数据, 如果数据异常标记出来
     */
    public boolean cleanAbnormalData(List<ETable> rawData) {
        if(rawData.isEmpty()) return false;
        for (ETable data : rawData) {
            // 表示已经预处理数据
            data.setDealStatus(true);
            // 新增tank_number非空校验
            boolean isTankNumberValid = data.getTankNumber() != null && data.getTankNumber() > 0;
            // 原有校验 + 新增的罐体编号校验
            if (!isTankNumberValid || !CheckTemperature(data) || !CheckPh(data) ||
                    !CheckAceticAcid(data) || !CheckAlcohol(data)) {
                data.setAbnormalNum(true);
            }
        }
        return true;
    }

//    /**
//     * 填充缺失值
//     */
//    public List<ETable> fillMissingValues(List<ETable> dataList) {
//        if (dataList == null || dataList.size() <= 1) {
//            return dataList;
//        }
//
//        for (int i = 0; i < dataList.size(); i++) {
//            ETable current = dataList.get(i);
//
//            // 如果当前数据有缺失，尝试用前后数据的平均值填充
//            if (hasMissingValues(current)) {
//                ETable prev = getPreviousValidData(dataList, i);
//                ETable next = getNextValidData(dataList, i);
//
//                if (prev != null && next != null) {
//                    fillWithAverage(current, prev, next);
//                } else if (prev != null) {
//                    fillWithPrevious(current, prev);
//                } else if (next != null) {
//                    fillWithNext(current, next);
//                }
//            }
//        }
//
//        return dataList;
//    }

    /**
     * 数据标准化处理, 计算相对于设置的值的偏移量
     */
    public List<ETable> normalizeData(List<ETable> dataList) {
        if (dataList == null || dataList.isEmpty()) {
            return dataList;
        }

        // 计算各参数的最大值和最小值
        calculateMinMaxValues(dataList);

        // 对每个数据点进行标准化
        for (ETable data : dataList) {
            normalizeTemperature(data);
            normalizePh(data);
            normalizeAceticAcid(data);
            normalizeAlcohol(data);
        }

        return dataList;
    }

    // 修改原有校验方法中的常量引用为成员变量
    // 私有工具方法
    // 检查温度异常值
    private boolean CheckTemperature(ETable source) {
        BigDecimal temp = source.getTemperature();
        if (temp == null || temp.compareTo(tempMin) < 0 || temp.compareTo(tempMax) > 0) {
            return false;
        }
        return true;
    }

    // 检查PH异常值
    private boolean CheckPh(ETable source) {
        BigDecimal ph = source.getPhValue();
        if (ph == null || ph.compareTo(phMin) < 0 || ph.compareTo(phMax) > 0) {
            return false;
        }
        return true;
    }

    // 检查醋酸含量异常值
    private boolean CheckAceticAcid(ETable source) {
        BigDecimal acetic = source.getAceticAcid();
        if (acetic == null || acetic.compareTo(aceticMin) < 0 || acetic.compareTo(aceticMax) > 0) {
            return false;
        }
        return true;
    }

    // 检查酒精含量异常值
    private boolean CheckAlcohol(ETable source) {
        BigDecimal alcohol = source.getAlcohol();
        if (alcohol == null || alcohol.compareTo(alcoholMin) < 0 || alcohol.compareTo(alcoholMax) > 0) {
            return false;
        }
        return true;
    }



//    private boolean hasMissingValues(ETable data) {
//        return data.getTemperature() == null ||
//                data.getPh() == null ||
//                data.getAceticAcid() == null ||
//                data.getOxygenContent() == null;
//    }

//    private ETable getPreviousValidData(List<ETable> dataList, int index) {
//        for (int i = index - 1; i >= 0; i--) {
//            if (!hasMissingValues(dataList.get(i))) {
//                return dataList.get(i);
//            }
//        }
//        return null;
//    }

//    private ETable getNextValidData(List<ETable> dataList, int index) {
//        for (int i = index + 1; i < dataList.size(); i++) {
//            if (!hasMissingValues(dataList.get(i))) {
//                return dataList.get(i);
//            }
//        }
//        return null;
//    }

//    private void fillWithAverage(ETable target, ETable prev, ETable next) {
//        // 温度平均值
//        if (target.getTemperature() == null) {
//            BigDecimal avg = prev.getTemperature().add(next.getTemperature())
//                    .divide(new BigDecimal("2"), 2, RoundingMode.HALF_UP);
//            target.setTemperature(avg);
//        }
//
//        // pH平均值
//        if (target.getPh() == null) {
//            BigDecimal avg = prev.getPh().add(next.getPh())
//                    .divide(new BigDecimal("2"), 2, RoundingMode.HALF_UP);
//            target.setPh(avg);
//        }
//
//        // 醋酸浓度平均值
//        if (target.getAceticAcid() == null) {
//            BigDecimal avg = prev.getAceticAcid().add(next.getAceticAcid())
//                    .divide(new BigDecimal("2"), 2, RoundingMode.HALF_UP);
//            target.setAceticAcid(avg);
//        }
//    }
//
//    private void fillWithPrevious(ETable target, ETable prev) {
//        if (target.getTemperature() == null) {
//            target.setTemperature(prev.getTemperature());
//        }
//        if (target.getPh() == null) {
//            target.setPh(prev.getPh());
//        }
//        if (target.getAceticAcid() == null) {
//            target.setAceticAcid(prev.getAceticAcid());
//        }
//    }
//
//    private void fillWithNext(ETable target, ETable next) {
//        if (target.getTemperature() == null) {
//            target.setTemperature(next.getTemperature());
//        }
//        if (target.getPh() == null) {
//            target.setPh(next.getPh());
//        }
//        if (target.getAceticAcid() == null) {
//            target.setAceticAcid(next.getAceticAcid());
//        }
//    }

    private void calculateMinMaxValues(List<ETable> dataList) {
        // 实际实现中应计算数据集中的真实最大最小值
    }

    private void normalizeTemperature(ETable data) {
        // 标准化实现 (x - min) / (max - min)
        if (data.getTemperature() != null) {
            BigDecimal normalized = data.getTemperature().subtract(tempMin)
                    .divide(tempMax.subtract(tempMin), 4, RoundingMode.HALF_UP);
            data.setTemperature(normalized);
        }
    }

    private void normalizePh(ETable data) {
        if (data.getPhValue() != null) {
            BigDecimal normalized = data.getPhValue().subtract(phMin)
                    .divide(phMax.subtract(phMin), 4, RoundingMode.HALF_UP);
            data.setPhValue(normalized);
        }
    }

    private void normalizeAceticAcid(ETable data) {
        if (data.getAceticAcid() != null) {
            BigDecimal normalized = data.getAceticAcid().subtract(aceticMin)
                    .divide(aceticMax.subtract(aceticMin), 4, RoundingMode.HALF_UP);
            data.setAceticAcid(normalized);
        }
    }

    private void normalizeAlcohol(ETable data) {
        if (data.getAlcohol() != null) {
            BigDecimal normalized = data.getAlcohol().subtract(alcoholMin)
                    .divide(alcoholMax.subtract(alcoholMin), 4, RoundingMode.HALF_UP);
            data.setAceticAcid(normalized);
        }
    }


}